﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Models;
using System.Threading;
using ChinaDynastyTours.Helpers;

namespace ChinaDynastyTours.Views
{
    public partial class TravelOrderForm : DevExpress.XtraEditors.XtraForm
    {
        //输入参数
        public string _TourGroupID { get; set; }//团ID
        public string _TourGroupState { get; set; }//团状态
        public int _TourGroupScheduleID { get; set; }//行程计划ID
        
        /// <summary>
        /// 团的成人数，作为人数输入进来
        /// </summary>
        public int _AdultNum { set { tbAmount.EditValue = value; } }

        private int _ExpenseID;//费用ID,用于判定当前选定的行程计划是否存在宾馆预定及费用信息
        private DataTable _dtTravelOrderData;//钱款信息，
        
        //输出参数
        public string ReturnTravelAgencyID { get; set; }
        public string ReturnTravelAgencyName { get; set; }
        public string ReturnContact { get; set; }

        public TravelOrderForm(string desCityName)
        {
            InitializeComponent();

            tbCityName.EditValue = desCityName;
        }

        private void LoadData()
        {
            travelAgencyGridControl.DataSource = BaseInfoCtrl.GetProviderData(new ProviderTypeEnum[] { ProviderTypeEnum.旅行社 }, CN2PYHelper.CapitalCovert(tbCityName.Text), CN2PYHelper.CapitalCovert(tbProviderName.Text));
        }

        private void TravelOrderForm_Load(object sender, EventArgs e)
        {
            //初始化旅行社数据
            //travelAgencyGridControl.DataSource = BaseInfoCtrl.GetProviderData(new ProviderTypeEnum[] { ProviderTypeEnum.旅行社 });
            LoadData();

            lblTourGroupState.Text = _TourGroupState;
            lblTourGroupID.Text = _TourGroupID;

            //获取指定计划号的预订数据信息
            _dtTravelOrderData = TravelOrderCtrl.GetTravelOrderData(_TourGroupScheduleID);

            InitializeGUIData();
        }

        private void InitializeGUIData()
        {
            //获取行程计划对应的宾馆预定信息
            if (_dtTravelOrderData != null && _dtTravelOrderData.Rows.Count > 0)
            {
                //与UI绑定
                tbBudget.DataBindings.Add("EditValue", _dtTravelOrderData, "Budget");
                tbSinglePrice.DataBindings.Add("EditValue", _dtTravelOrderData, "SinglePrice");
                tbAmount.DataBindings.Add("EditValue", _dtTravelOrderData, "Amount");

                //取得费用标识
                _ExpenseID = int.Parse(_dtTravelOrderData.Rows[0]["ExpenseID"].ToString());

                //设定焦点行
                string providerId = _dtTravelOrderData.Rows[0]["ProviderID"].ToString();
                for (int i = 0; i < travelAgencyGridView.RowCount; i++)
                {
                    if (providerId == travelAgencyGridView.GetRowCellValue(i, "ProviderID").ToString())
                        travelAgencyGridView.FocusedRowHandle = i;
                }
                
            }
            else
                _ExpenseID = -1;
        }

        private void travelAgencyGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0) return;

            string providerId = travelAgencyGridView.GetDataRow(e.FocusedRowHandle)["ProviderID"].ToString();
            if (string.IsNullOrEmpty(providerId)) return;
            travelServiceGridControl.DataSource = ServiceInfoCtrl.GetTravelAgentServiceData(providerId);
        }
        private void travelServiceGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            //双击服务表格，将单价写入文本框中
            if (e.Clicks == 2)
                tbSinglePrice.EditValue = travelServiceGridView.GetDataRow(travelServiceGridView.FocusedRowHandle)["Price"];
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            int amount = int.Parse(tbAmount.EditValue.ToString());
            decimal singlePrice = decimal.Parse(tbSinglePrice.EditValue.ToString());
            tbBudget.EditValue = amount * singlePrice;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {

            int providerID = int.Parse(travelAgencyGridView.GetDataRow(travelAgencyGridView.FocusedRowHandle)["ProviderID"].ToString());
            string providerName = travelAgencyGridView.GetDataRow(travelAgencyGridView.FocusedRowHandle)["ProviderName"].ToString();
            string serviceName = travelServiceGridView.FocusedRowHandle < 0 ? "" : travelServiceGridView.GetDataRow(travelServiceGridView.FocusedRowHandle)["ServiceName"].ToString();
            decimal budget = decimal.Parse(tbBudget.EditValue.ToString());

            //创建地接社预定信息内容
            TravelOrderEntity travelOrder = new TravelOrderEntity()
            {
                Amount = tbAmount.Text == "" ? 0 : int.Parse(tbAmount.Text),
                //TravelOrderID==
                City = travelAgencyGridView.GetDataRow(travelAgencyGridView.FocusedRowHandle)["City"].ToString(),
                ServiceName = chkSelectedService.Checked == true ? "" : serviceName,
                SinglePrice = tbSinglePrice.EditValue.ToString() == "" ? 0 : decimal.Parse(tbSinglePrice.EditValue.ToString()),//.Parse(travelAgencyGridView.GetDataRow(travelAgencyGridView.FocusedRowHandle)["SinglePrice"].ToString()),
                ProviderID = providerID,
                ProviderName = providerName,
                ExpenseID = _ExpenseID,
                TourgroupID = _TourGroupID,
                TourGroupScheduleID = _TourGroupScheduleID,
                ContractPath = lblContractPath.Text

            };

            if (_ExpenseID == -1) //无对应地接社预定及相关费用信息，创建新的内容
            {
                //创建费用
                ExpenseEntity expense = new ExpenseEntity()
                {
                    //ExpenseID = _ExpenseID,
                    TourgroupID = _TourGroupID,
                    TourgroupName=TeamGroupCtrl.GetTeamGroupNameById(_TourGroupID),
                    ProviderID = providerID,
                    ProviderName = providerName,
                    ServiceName = serviceName == "" ? providerName : serviceName,
                    Budget = budget,
                    PayTotal = 0,
                    ApplyPayTotal = 0,
                    AdjustAmount = 0,
                    Status = ExpenseStatusEnum.计划.ToString(),
                    TypeBelong = ProviderTypeEnum.旅行社.ToString(),
                    ApplyPay = 0,
                    PayStatus = PayApplyStatusEnum.未付.ToString(),
                    CreateByUserName = Thread.CurrentPrincipal.Identity.Name,//UserInfoCtrl.GetNameByUserName(Thread.CurrentPrincipal.Identity.Name)
                    TourGroupScheduleID=_TourGroupScheduleID,
                    CreateTime=DateTime.Now.ToString("yyyy-MM-dd"),
                    ExpenseTypeID = 2,//所属费用类型(费用类型表中存储着编号，此编号是固定的，1房费、2团费、3餐费、4交通费、5门票、6杂费)
                    ExpenseType = BaseInfoCtrl.GetExpenseTypeNameByID(2)//同上
                };
                TravelOrderCtrl.CreateTravelOrderAndExpenseData(expense, travelOrder);
            }
            else//更新已有内容
            {

                ExpenseEntity expense = new ExpenseEntity()
                {
                    ExpenseID = _ExpenseID, /*重点字段*/
                    ProviderID = providerID,
                    ProviderName = providerName,
                    ServiceName = serviceName == "" ? providerName : serviceName,
                    Budget = decimal.Parse(tbBudget.EditValue.ToString()),
                    TypeBelong = ProviderTypeEnum.旅行社.ToString()
                };
                TravelOrderCtrl.UpdateTravelOrderData(expense, travelOrder);
                
            }
            //更新团审核成本
            TeamGroupCtrl.UpdateTourGroupBudgeCost(_TourGroupID);

            //返回行程计划显示信息
            ReturnTravelAgencyName = providerName;
            ReturnTravelAgencyID=providerID.ToString();
            ReturnContact=travelAgencyGridView.GetDataRow(travelAgencyGridView.FocusedRowHandle)["Contact"].ToString();
        }

        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void chkSelectedService_CheckedChanged(object sender, EventArgs e)
        {
            travelServiceGridControl.Enabled = !chkSelectedService.Checked;
        }


    }
}
